package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 获取经纬度
 */
@Component
public class CoordinateUtil {

    private static String baiduMapAk = "3jKPwf44qfSDMBIqqM1G0vuq";

    public static JSONObject getCoordinate(String region, String query) {
        JSONObject object = new JSONObject();
        String result = HttpClientUtil.doGet("https://api.map.baidu.com/place/v2/search?query=" + query + "&tag=&region=" + region + "&output=json&ak=" +
                baiduMapAk, String.class);
        if (null == result || ObjectUtils.isEmpty(result)) {
            throw new CustomException("region or address is error", 400);
        }
        JSONObject obj = JSONObject.parseObject(result);
        if (null == obj || obj.isEmpty() || !obj.containsKey("results") || ObjectUtils.isEmpty(obj.getString("results"))) {
            throw new CustomException("region or address is error", 400);
        }
        JSONArray array = obj.getJSONArray("results");
        JSONObject data = array.getJSONObject(0);
        if (null == data || data.isEmpty() || !data.containsKey("location")) {
            throw new CustomException("region or address is error", 400);
        }
        Double longitude = data.getJSONObject("location").getDouble("lng");
        Double latitude = data.getJSONObject("location").getDouble("lat");
        if (null == latitude || null == longitude) {
            throw new CustomException("region or address is error", 400);
        }
        object.put("longitude", longitude);
        object.put("latitude", latitude);
        return object;
    }
}
